﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using MSP.Business.UserManagement;
using MSP.Data.Domain;
using MSP.UI.Helpers;
using System.IO;
using DevExpress.XtraEditors.DXErrorProvider;


namespace MSP.UI
{
    public partial class xfrmUsers : DevExpress.XtraEditors.XtraForm
    {
        UserManager userManager = new UserManager();
        CurrencyManager manager;
        int LastFocusedRowHandle;

        public xfrmUsers()
        {
            InitializeComponent();
        }

        private void xfrmUsers_Load(object sender, EventArgs e)
        {
            LastFocusedRowHandle = -1;
            FormLoad();
        }

        void FormLoad()
        {
            dsUser1.User.Clear();
            List<User> users = userManager.GetAllUser().ToList();
            DataTable dtUsers = EnumerableExtension.ToDataTable(users);
            dtUsers.TableName = "User";
            foreach (DataRow item in dtUsers.Rows)
            {
                dsUser1.User.LoadDataRow(item.ItemArray, LoadOption.OverwriteChanges);
            }
            dsUser1.User.PrimaryKey = new DataColumn[] { dsUser1.User.Columns["Id"] };

            manager = dataLayoutControl1.BindingContext[dataLayoutControl1.DataSource, dataLayoutControl1.DataMember] as CurrencyManager;

            StatuLookupEdit.Properties.DataSource = userManager.GetAllUserStatu();
            StatuLookupEdit.Properties.DisplayMember = "Name";
            StatuLookupEdit.Properties.ValueMember = "Value";
            StatuLookupEdit.Properties.Columns.Clear();
            StatuLookupEdit.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Durumu"));

            UserTypeLookupEdit.Properties.DataSource = userManager.GetAllUserGroup();
            UserTypeLookupEdit.Properties.DisplayMember = "Name";
            UserTypeLookupEdit.Properties.ValueMember = "Value";
            UserTypeLookupEdit.Properties.Columns.Clear();
            UserTypeLookupEdit.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Grubu"));

            InitValidationRules();
            InitChangePasswordValidationRules();
        }

        private void InitChangePasswordValidationRules()
        {
            // <notEmptyPassword> 
            ConditionValidationRule notEmptyPasswordValidationRule = new ConditionValidationRule();
            notEmptyPasswordValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyPasswordValidationRule.ErrorText = "Lütfen şifre giriniz";
            // </notEmptyPassword>

            dxValidationProvider2.SetValidationRule(NewPasswordTextEdit, notEmptyPasswordValidationRule);
        }

        private void InitValidationRules()
        {
            // <notEmptyTextEdit> 
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = "Lütfen değer giriniz";
            // </notEmptyTextEdit>

            // <notSelectValidationRule>
            ConditionValidationRule notSelectValidationRule = new ConditionValidationRule();
            notSelectValidationRule.ConditionOperator = ConditionOperator.NotEquals;
            notSelectValidationRule.Value1 = null;
            notSelectValidationRule.ErrorText = "Lütfen seçiniz";
            // </notSelectValidationRule>

            // <emailValidationRule>
            ConditionValidationRule emailValidationRule = new ConditionValidationRule();
            emailValidationRule.ConditionOperator = ConditionOperator.Contains;
            emailValidationRule.Value1 = '@';
            emailValidationRule.ErrorText = "Lütfen geçerli email giriniz";
            emailValidationRule.ErrorType = ErrorType.Warning;
            // </emailValidationRule>


            //notEmptyValidationRule
            dxValidationProvider1.SetValidationRule(LoginTextEdit, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(NameTextEdit, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(SurnameTextEdit, notEmptyValidationRule);


            //notSelectValidationRule
            dxValidationProvider1.SetValidationRule(UserTypeLookupEdit, notSelectValidationRule);
            dxValidationProvider1.SetValidationRule(StatuLookupEdit, notSelectValidationRule);

            //emailValidationRule
            dxValidationProvider1.SetValidationRule(EmailTextEdit, emailValidationRule);

            dxValidationProvider1.ValidationMode = ValidationMode.Auto;

            

        }

        private void grdSearch_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            RowChanged(e.FocusedRowHandle);
        }

        void RowChanged(int FocusedRowHandle)
        {
            manager.CancelCurrentEdit();
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;
            NewPasswordTextEdit.Text = "";

            if (FocusedRowHandle >= 0)
            {
                DataRow dr = grdSearch.GetDataRow(FocusedRowHandle);
                int id = Convert.ToInt32(dr["Id"]);
                if (id >= 0)
                {

                    if (string.IsNullOrEmpty(dsUser1.User.DefaultView.Sort))
                    {
                        dsUser1.User.DefaultView.Sort = "Id";
                    }

                    DataRowView[] drwList = dsUser1.User.DefaultView.FindRows(id);

                    if (drwList != null && drwList.Length > 0)
                    {
                        int i = 0;
                        foreach (DataRowView drw in manager.List)
                        {
                            if (drw.Row == drwList[0].Row)
                            {
                                manager.Position = i;
                                break;
                            }
                            i++;
                        }
                    }
                }
            }
            else
            {

            }

            dxValidationProvider1.Validate();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            manager.AddNew();
            grdMaster.Enabled = false;
            btnNew.Enabled = false;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;

            IdTextEdit.Text = "0";

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult ds = MessageBox.Show("Silmek istediğize emin misiniz?","?",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            
            if (ds != DialogResult.Yes)
            {
                return;
            }

            DataRowView drv = (DataRowView)manager.Current;
            if (drv.Row.RowState != DataRowState.Detached)
            {
                drv.Row.SetModified();
                DataTable dtDeletedUsers = dsUser1.User.GetChanges(DataRowState.Modified);
                List<User> retList = EnumerableExtension.ToList<User>(dtDeletedUsers);
                if (retList.Count == 1)
                {
                    foreach (User item in retList)
                    {
                        bool result = userManager.DeleteUser(item);
                    }
                }

                LastFocusedRowHandle = grdSearch.FocusedRowHandle - 1;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else
            {
                manager.CancelCurrentEdit();
            }
            RowChanged(grdSearch.FocusedRowHandle);
            grdMaster.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate())
            {
                return;
            }
            manager.EndCurrentEdit();

            DataRowView drv = (DataRowView)manager.Current;

            if (drv.Row.RowState == DataRowState.Added)
            {
                DataTable dtAddedUsers = drv.Row.Table.GetChanges(DataRowState.Added);
                List<User> retList = EnumerableExtension.ToList<User>(dtAddedUsers);

                foreach (User item in retList)
                {
                    int id = userManager.SaveUser(item);

                }
                LastFocusedRowHandle = dsUser1.User.Count - 1;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else if (drv.Row.RowState == DataRowState.Modified)
            {
                DataTable dtEditedUsers = drv.Row.Table.GetChanges(DataRowState.Modified);
                List<User> retList = EnumerableExtension.ToList<User>(dtEditedUsers);

                foreach (User item in retList)
                {
                    bool result = userManager.UpdateUser(item);
                }
                LastFocusedRowHandle = grdSearch.FocusedRowHandle;
                FormLoad();
                grdSearch.FocusedRowHandle = LastFocusedRowHandle;
            }
            else if (drv.Row.RowState == DataRowState.Deleted)
            {

            }

            grdMaster.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;
        }

        private void btnChangePassword_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider2.Validate())
            {
                return;
            }

            int id = Convert.ToInt32(IdTextEdit.Text);

            if (id > 0)
	        {
                User user = userManager.GetUserById(id);
                user.Password = NewPasswordTextEdit.Text;
                userManager.UpdateUser(user);
	        }
            

        }
    }
}